package com.nsgf.library.ui.page.home;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.AnnouncementBean;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.DeviceOpeningBean;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WaterLevelByCodeBean;
import com.nsgf.library.data.bean.WeatherDetailBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.bean.XBannerBeanInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.FragmentNsgfHomeBinding;
import com.nsgf.library.databinding.ItemTextBinding;
import com.nsgf.library.databinding.LayoutSpinnerPopupBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.photopicker.PhotoPreview;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.ui.adapter.DeviceStatusAdapter;
import com.nsgf.library.ui.adapter.HomeLabelGateListAdapter;
import com.nsgf.library.ui.adapter.HomeLabelListAdapter;
import com.nsgf.library.ui.adapter.NoticeAnnouncementHomeAdapter;
import com.nsgf.library.ui.adapter.SimpleDataBindingPositionAdapter;
import com.nsgf.library.ui.adapter.ViewHolder;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.DutyManagementActivity;
import com.nsgf.library.ui.page.MessageDetailsActivity;
import com.nsgf.library.ui.page.MessageWarningActivity;
import com.nsgf.library.ui.page.NoticeAnnouncementDetailActivity;
import com.nsgf.library.ui.page.NoticeAnnouncementListActivity;
import com.nsgf.library.ui.page.PatrolObjectSelectionActivity;
import com.nsgf.library.ui.page.ProjectOverviewActivity;
import com.nsgf.library.ui.page.RainDetailActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.WaterActivity;
import com.nsgf.library.ui.page.video.VideoListActivity;
import com.nsgf.skjz.utils.StringUtil;
import com.nsgf.skjz.utils.ToastUtils;
import com.stx.xhb.xbanner.XBanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class HomeFragment extends BaseFragment {

    private HomeFragmentStates mStates;

    private FragmentNsgfHomeBinding mBinding;

    private HomeLabelListAdapter mAdapter;
    private HomeLabelGateListAdapter mAdapterGate;
    private DeviceStatusAdapter mDeviceStatusAdapter;
    private NoticeAnnouncementHomeAdapter mNoticeAdapter;
    private List<LibraryInfo> mDatas = new ArrayList<>();

    private AccountRequester mAccountRequester;

    // 设备状态筛选相关
    private List<DeviceOpeningBean> mAllDeviceStatusList = new ArrayList<>();
    private List<String> mFilterOptions = new ArrayList<>();
    private PopupWindow mDeviceStatusFilterPopup;
    private LayoutSpinnerPopupBinding mDeviceStatusFilterPopupBinding;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(HomeFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new HomeLabelListAdapter(getContext());

        mAdapter.setOnItemClickListener((viewId, item, position) -> {
            Intent intent;
            EventMsg eventMsg = new EventMsg();
            switch (position) {
                case 0:
                    intent = new Intent(getActivity(), ProjectOverviewActivity.class);
                    intent.putExtra("title", "工程信息");
                    startActivity(intent);
                    break;
                case 1:
                    intent = new Intent(getActivity(), DutyManagementActivity.class);
                    startActivity(intent);
                    break;
                case 2:
                    intent = new Intent(getActivity(), WaterActivity.class);
                    startActivity(intent);
                    break;
                case 3:
                    intent = new Intent(getActivity(), RainDetailActivity.class);
                    intent.putExtra("title", "雨量监测");
                    startActivity(intent);
                    break;
                case 4:
                    // 跳转到巡查对象选择页面
                    intent = new Intent(getActivity(), PatrolObjectSelectionActivity.class);
                    startActivity(intent);
                    break;
                case 5:
                    intent = new Intent(getActivity(), VideoListActivity.class);
                    startActivity(intent);
                    break;
                case 6:
//
//                    intent = new Intent(getActivity(), WebViewActivity.class);
//                    intent.putExtra("url", H5_DUTY_RECORD);
//                    intent.putExtra("title", "值班管理");
//                    startActivity(intent);
                    intent = new Intent(getActivity(), MessageWarningActivity.class);
                    startActivity(intent);
                    break;
                case 7:

                    intent = new Intent(getActivity(), NoticeAnnouncementListActivity.class);
                    startActivity(intent);
                    break;
            }
        });
        mAdapterGate = new HomeLabelGateListAdapter(getContext());
        mDeviceStatusAdapter = new DeviceStatusAdapter(getContext());
        mNoticeAdapter = new NoticeAnnouncementHomeAdapter(getContext());

        // 设置通知公告列表项点击事件
        mNoticeAdapter.setOnItemClickListener((viewId, item, position) -> {
            Intent intent = new Intent(getActivity(), NoticeAnnouncementDetailActivity.class);
            intent.putExtra("id", item.getId());
            // 传递原始创建时间（保存在updateTime字段中）
            if (item.getUpdateTime() != null) {
                intent.putExtra("createTime", item.getUpdateTime());
            }
            startActivity(intent);
        });

        return new DataBindingConfig(R.layout.fragment_nsgf_home, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.adapterGate, mAdapterGate)
                .addBindingParam(BR.adapterDeviceStatus, mDeviceStatusAdapter)
                .addBindingParam(BR.adapterNotice, mNoticeAdapter);
    }

    private List<XBannerBeanInfo> banners = new ArrayList<>();

    private List<Fragment> fragmentList = new ArrayList<>();

    private String[] mPageTitleList;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("refreshHome".equals(event.getMsg())) {
            onRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        EventBus.getDefault().register(this);
        getLifecycle().addObserver(mAccountRequester);

        mDatas.add(new LibraryInfo("工程概况", "", "", R.drawable.ic_nsgf_home_label_info));
        mDatas.add(new LibraryInfo("值班管理", "", "", R.drawable.ic_nsgf_home_label_job));
        mDatas.add(new LibraryInfo("水情监测", "", "", R.drawable.ic_nsgf_home_label_water));
        mDatas.add(new LibraryInfo("雨情监测", "", "", R.drawable.ic_nsgf_home_label_rain));
        mDatas.add(new LibraryInfo("工程巡查", "", "", R.drawable.ic_home_label_inspect));
        mDatas.add(new LibraryInfo("视频监控", "", "", R.drawable.ic_nsgf_home_label_video));
        mDatas.add(new LibraryInfo("告警信息", "", "", R.drawable.ic_nsgf_home_label_warning));
        mDatas.add(new LibraryInfo("通知公告", "", "", R.drawable.ic_nsgf_home_label_message));


        mStates.list.set(mDatas);
        mAdapter.notifyDataSetChanged();

        mBinding = (FragmentNsgfHomeBinding) getBinding();


        mAccountRequester.getReservoirResult().observe(this, dataResult -> {

            if (dataResult.getResponseCode() == 200) {

                if (!StringUtil.isEmpty(dataResult.getData().getArea())) {

                    String[] area = dataResult.getData().getArea().split(",");
                    UserInfo.getInstance().setProjectLat(area[1]);
                    UserInfo.getInstance().setProjectLon(area[0]);
                }
                banners.clear();
                if (null != dataResult.getData().getFiles()) {
                    for (WorkOrderDetailBean.FileDto fileDto : dataResult.getData().getFiles()) {
                        banners.add(new XBannerBeanInfo(APIs.BASE_URL_IMG + fileDto.getFilePath()));
                    }
                    mBinding.xbanner.setBannerData(banners);
                    mBinding.xbanner.loadImage((banner, model, view, position) -> {
                        String url = (String) ((XBannerBeanInfo) model).getXBannerUrl();
                        GlideImgManager.getInstance().glideLoaderBannerCenterCrop(getActivity(), url.replace("\\", "/"), (ImageView) view, 10);

                    });
                    mBinding.xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                        @Override
                        public void onItemClick(XBanner banner, Object model, View view, int position) {
                            ArrayList<WorkOrderDetailBean.FileDto> fileDtos = new ArrayList<>();
                            WorkOrderDetailBean.FileDto fileDto = new WorkOrderDetailBean.FileDto();
                            fileDto.setFilePath(banners.get(position).getXBannerUrl().toString());
                            fileDtos.add(fileDto);
                            PhotoPreview.builder().setPhotos(fileDtos).setAction(MultiPickResultView.ACTION_ONLY_SHOW).start(getActivity());
                        }
                    });
                }
                mAccountRequester.homeUnreadCount(UserInfo.getInstance().getProjectCode());

            } else {

                if (401 == dataResult.getResponseCode()) {
                    UserInfo.getInstance().clearUserInfo();
                    getActivity().finish();
                }
            }
        });
        mAccountRequester.getMessageWarningResult().observe(this, dataResult -> {
            if (dataResult.getResponseCode() == 200) {

                if (!dataResult.getData().isEmpty()) {
                    mStates.notice.set(dataResult.getData().get(dataResult.getData().size() - 1).getTitle());
                    mStates.noticeTime.set(dataResult.getData().get(dataResult.getData().size() - 1).getCreateTime());
                    mStates.noticeId.set(dataResult.getData().get(dataResult.getData().size() - 1).getId());

                }

            }
        });


        mAccountRequester.getNoticeListResult().observe(this, responseStatus -> {
            if (responseStatus.getResponseCode() == 200) {
                AnnouncementBean data = responseStatus.getData();
                if (data != null && data.getRecords() != null && !data.getRecords().isEmpty()) {
                    // 格式化日期并创建新列表，同时保存原始时间
                    List<AnnouncementBean.RecordBean> formattedList = new ArrayList<>();
                    for (AnnouncementBean.RecordBean record : data.getRecords()) {
                        AnnouncementBean.RecordBean newRecord = new AnnouncementBean.RecordBean();
                        newRecord.setId(record.getId());
                        newRecord.setAnnouncementTopic(record.getAnnouncementTopic());
                        newRecord.setDescription(record.getDescription());
                        newRecord.setImage(record.getImage());
                        newRecord.setImageList(record.getImageList());
                        newRecord.setVideo(record.getVideo());
                        newRecord.setVideoList(record.getVideoList());
                        newRecord.setFile(record.getFile());
                        newRecord.setFileList(record.getFileList());
                        newRecord.setCreateBy(record.getCreateBy());
                        // 保存原始时间到updateTime字段（用于传递给详情页），显示时间格式化
                        newRecord.setUpdateTime(record.getCreateTime()); // 保存原始时间
                        newRecord.setCreateTime(formatDate(record.getCreateTime())); // 显示格式化时间
                        newRecord.setUpdateBy(record.getUpdateBy());
                        newRecord.setIsDelete(record.getIsDelete());
                        newRecord.setIsRead(record.getIsRead());
                        formattedList.add(newRecord);
                    }
                    mStates.noticeList.set(formattedList);
                } else {
                    mStates.noticeList.set(new ArrayList<>());
                }
            } else {
                if (401 == responseStatus.getResponseCode()) {
                    UserInfo.getInstance().clearUserInfo();
                    getActivity().finish();
                }
            }
        });

        mAccountRequester.getLibraryList().observe(this, new Observer<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onChanged(ResponseStatus<List<LibraryInfo>> dataResult) {

                if (dataResult.getResponseCode() == 200) {

                    if (null != dataResult.getData()) {
                        if (dataResult.getData().size() > 0) {

                            mStates.listGate.set(dataResult.getData());

                            mBinding.notdata.setVisibility(View.GONE);
                        } else {
                            mStates.listGate.set(new ArrayList<>());
                            mBinding.notdata.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    ToastUtils.showLongToast(dataResult.getMsg());
                }
            }
        });

        //获取消息统计
        mAccountRequester.getStatisticsNewResult().observe(this, dataResult -> {

            mBinding.swipeRefreshLayout.setRefreshing(false);
            if (dataResult.getResponseCode() == 200) {
                mAdapter.getCurrentList().get(6).setBadge(dataResult.getData().getWarningNum());
                mAdapter.getCurrentList().get(7).setBadge(dataResult.getData().getNotice());
            } else {
                ToastUtils.showLongToast(dataResult.getMsg());
            }
        });
        mAccountRequester.getDeviceOpeningResult().observe(this, listResponseStatus -> {
            if (listResponseStatus.getResponseCode() == 200) {
                if (listResponseStatus.getData() != null) {
                    mAllDeviceStatusList = listResponseStatus.getData();

                    // 根据选中的筛选条件过滤数据
                    filterDeviceStatusList();
                } else {
                    mFilterOptions.clear();
                    mStates.listDeviceStatus.set(new ArrayList<>());
                    mStates.selectedFilterName.set("");
                    mDeviceStatusAdapter.notifyDataSetChanged();
                }
            } else {
                ToastUtils.showLongToast(listResponseStatus.getMsg());
            }
        });

        RxBus.get().toObservable().map((Function<Object, EventMsg>) o -> (EventMsg) o).subscribe((Consumer<EventMsg>) eventMsg -> {
            if (eventMsg != null) {

                if ("warning".equals(eventMsg.getMsg())) {
                    mAccountRequester.homeUnreadCount(UserInfo.getInstance().getProjectCode());
                }
            }
        });
        mAccountRequester.getWeatherDetailBean().observe(this, weatherDetailBeanResponseStatus -> {

            if (weatherDetailBeanResponseStatus.getResponseCode() == 200) {

                WeatherDetailBean.DataBeanX.DataBean.ForecastBean forecastBean = weatherDetailBeanResponseStatus.getData().getData().getData().getForecast().get(0);
                mStates.weatherTitle.set(forecastBean.getType() + forecastBean.getLow() + " ~ " + forecastBean.getHigh() + "  I  " + forecastBean.getFx() + forecastBean.getFl());
                mStates.weatherIcont.set(getItemIcon(forecastBean.getType()));

            } else {
                mStates.weatherTitle.set("晴26℃  I  东南风2级");
            }

        });

        mBinding.swipeRefreshLayout.setOnRefreshListener(() -> HomeFragment.this.onRefresh());

        mAccountRequester.getUserResultProject().observe(this, userInfoResponseStatus -> {
            if (userInfoResponseStatus.getResponseCode() == 200) {

                UserInfo.getInstance().setDeptName(userInfoResponseStatus.getData().getAdmin().getDeptName());
                userInfo = userInfoResponseStatus.getData();

                if (!userInfo.getProjectList().isEmpty()) {
                    mStates.projectName.set(userInfo.getProjectList().get(0).getItemText());
                    UserInfo.getInstance().setProjectCode(userInfo.getProjectList().get(0).getId());
                    UserInfo.getInstance().setFacilityType(userInfo.getProjectList().get(0).getFacilityType());
                    UserInfo.getInstance().setProjectName(userInfo.getProjectList().get(0).getItemText());
                    mStates.appLog.set(userInfo.getProjectList().get(0).getPictureUrlSrc());
                }
            }
            onRefresh();
        });

        mAccountRequester.getNewLoginInfo();

        mAccountRequester.getWaterLevelByCodeResult().observe(this, new Observer<ResponseStatus<WaterLevelByCodeBean>>() {
            @Override
            public void onChanged(ResponseStatus<WaterLevelByCodeBean> responseStatus) {
                if (responseStatus.getResponseCode() == 200) {
                    mStates.waterLevelByCodeBeanState.set(responseStatus.getData());
                }
            }
        });
    }

    public UserInfo userInfo;

    /**
     * 格式化日期：从 "2025-11-06 10:48:21" 转换为 "2025年11月6日"
     */
    private String formatDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) {
            return "";
        }
        try {
            // 提取日期部分（去掉时间部分）
            String datePart = dateStr.split(" ")[0];
            String[] parts = datePart.split("-");
            if (parts.length == 3) {
                int year = Integer.parseInt(parts[0]);
                int month = Integer.parseInt(parts[1]);
                int day = Integer.parseInt(parts[2]);
                return year + "年" + month + "月" + day + "日";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    private void onRefresh() {

        // 获取水库信息
        mAccountRequester.reservoirInfo(UserInfo.getInstance().getProjectCode(), UserInfo.getInstance().getFacilityType());
        mAccountRequester.getWarningMessage(UserInfo.getInstance().getProjectCode(), "", "");
        // 获取通知公告列表
        mAccountRequester.queryNoticeList(1);
        mAccountRequester.getDeviceOpening(UserInfo.getInstance().getProjectCode());
        mAccountRequester.queryWeatherForecast();

        mAccountRequester.homeUnreadCount(UserInfo.getInstance().getProjectCode());
        mAccountRequester.queryNoticeList(1);
        mAccountRequester.getWaterLevelByCode(UserInfo.getInstance().getProjectCode());

    }


    public Drawable getItemIcon(String type) {
        switch (type) {
            case "暴雪":
                return getActivity().getResources().getDrawable(R.drawable.baoxue);
            case "暴雨":
                return getActivity().getResources().getDrawable(R.drawable.baoyu);
            case "大暴雨":
                return getActivity().getResources().getDrawable(R.drawable.dabaoyu);
            case "大雪":
                return getActivity().getResources().getDrawable(R.drawable.daxue);
            case "大雨":
                return getActivity().getResources().getDrawable(R.drawable.dayu);
            case "冻雨":
                return getActivity().getResources().getDrawable(R.drawable.dongyu);
            case "多云":
                return getActivity().getResources().getDrawable(R.drawable.duoyun);
            case "浮沉":
                return getActivity().getResources().getDrawable(R.drawable.fuchen);
            case "雷阵雨":
                return getActivity().getResources().getDrawable(R.drawable.leizhenyu);
            case "雷阵雨伴有冰雹":
                return getActivity().getResources().getDrawable(R.drawable.lzybybb);
            case "霾":
                return getActivity().getResources().getDrawable(R.drawable.mai);
            case "强沙尘暴":
                return getActivity().getResources().getDrawable(R.drawable.qiangshachenbao);
            case "晴":
                return getActivity().getResources().getDrawable(R.drawable.qing);
            case "沙暴":
                return getActivity().getResources().getDrawable(R.drawable.shabao);
            case "沙尘暴":
                return getActivity().getResources().getDrawable(R.drawable.shachenbao);
            case "特大暴雨":
                return getActivity().getResources().getDrawable(R.drawable.tedabaoyu);
            case "雾":
                return getActivity().getResources().getDrawable(R.drawable.wu);
            case "小雪":
                return getActivity().getResources().getDrawable(R.drawable.xiaoxue);
            case "小雨":
                return getActivity().getResources().getDrawable(R.drawable.xiaoyu);
            case "阴":
                return getActivity().getResources().getDrawable(R.drawable.yin);
            case "雨夹雪":
                return getActivity().getResources().getDrawable(R.drawable.yujiaxue);
            case "阵雪":
                return getActivity().getResources().getDrawable(R.drawable.zhenxue);
            case "阵雨":
                return getActivity().getResources().getDrawable(R.drawable.zhenyu);
            case "中雪":
                return getActivity().getResources().getDrawable(R.drawable.zhongxue);
            case "中雨":
                return getActivity().getResources().getDrawable(R.drawable.zhongyu);
            default:
                return getActivity().getResources().getDrawable(R.drawable.qing);
        }
    }

    public static class HomeFragmentStates extends StateHolder {

        public final State<String> name = new State<>(UserInfo.getInstance().getName());
        public final State<String> notice = new State<>("");
        public final State<String> noticeTime = new State<>("");
        public final State<String> noticeId = new State<>("");
        public final State<List<LibraryInfo>> list = new State<>(new ArrayList<>());
        public final State<List<LibraryInfo>> listGate = new State<>(new ArrayList<>());
        public final State<List<LibraryInfo>> listGateTitle = new State<>(new ArrayList<>());
        public final State<List<DeviceOpeningBean.Devices>> listDeviceStatus = new State<>(new ArrayList<>());
        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<ClockInBean.DataBean> statistics = new State<>(null);
        public final State<WaterLevelByCodeBean> waterLevelByCodeBeanState = new State<>(null);
        public final State<String> weatherTitle = new State<>("");
        public final State<Drawable> weatherIcont = new State<>(null);
        public final State<String> selectedFilterName = new State<>("");
        public final State<List<AnnouncementBean.RecordBean>> noticeList = new State<>(new ArrayList<>());


    }

    private PopupWindow popupWindow;
    LayoutSpinnerPopupBinding spinnerPopupBinding;

    /**
     * 根据选中的筛选条件过滤设备状态列表
     */
    private void filterDeviceStatusList() {
        if (!mAllDeviceStatusList.isEmpty()) {

            List<DeviceOpeningBean.Devices> filteredList = mAllDeviceStatusList.get(0).getDevices();

            mStates.listDeviceStatus.set(filteredList);
            mDeviceStatusAdapter.notifyDataSetChanged();
        }
    }

    public class ClickProxy {

        public void openNotice() {

            if (StringUtil.isEmpty(mStates.noticeId.get()))
                return;
            Intent intent = new Intent(getActivity(), MessageDetailsActivity.class);
            intent.putExtra("title", mStates.notice.get());
            intent.putExtra("id", mStates.noticeId.get());
            intent.putExtra("warning", true);
            startActivity(intent);
        }

        /**
         * 切换水库
         */
        public void wayProject() {

            if (null == userInfo) return;
            if (null == userInfo.getProjectList())
                return;
            if (null == popupWindow) {
                popupWindow = new PopupWindow(getActivity());
                View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_spinner_popup, null);

                spinnerPopupBinding = DataBindingUtil.bind(popupView);
                // 创建PopupWindow实例
                popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                // 设置PopupWindow可以获得焦点，否则无法响应点击事件
                popupWindow.setFocusable(true);
                SimpleDataBindingPositionAdapter<UserInfo.ProjectListBean, ItemTextBinding> popupAdapter = new SimpleDataBindingPositionAdapter<UserInfo.ProjectListBean, ItemTextBinding>(getActivity(), R.layout.item_text, new DiffUtil.ItemCallback<UserInfo.ProjectListBean>() {
                    @Override
                    public boolean areItemsTheSame(@NonNull UserInfo.ProjectListBean oldItem, @NonNull UserInfo.ProjectListBean newItem) {
                        return false;
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull UserInfo.ProjectListBean oldItem, @NonNull UserInfo.ProjectListBean newItem) {
                        return false;
                    }
                }) {
                    @Override
                    protected void onBindItem(ItemTextBinding binding, UserInfo.ProjectListBean item, ViewHolder holder, int position) {
                        binding.setVm(item);
                    }
                };

                popupAdapter.submitList(userInfo.getProjectList());
                spinnerPopupBinding.setAdapter(popupAdapter);
                popupAdapter.setOnItemClickListener((viewId, item, position) -> {

                    mStates.projectName.set(item.getItemText());
                    UserInfo.getInstance().setProjectCode(item.getId());
                    UserInfo.getInstance().setFacilityType(item.getFacilityType());
                    UserInfo.getInstance().setProjectName(item.getItemText());
                    mStates.appLog.set(item.getPictureUrlSrc());
                    onRefresh();
                    popupWindow.dismiss();

                    EventMsg eventMsg = new EventMsg();
                    eventMsg.setMsg("warning");
                    RxBus.get().post(eventMsg);
                    EventBus.getDefault().post(eventMsg);
                });
            }

            // 显示下拉弹窗
            popupWindow.showAsDropDown(mBinding.tvNsgfHomeProject, 0, 0);


        }

        /**
         * 设备状态筛选点击事件
         */
        public void onDeviceStatusFilterClick() {
            if (mFilterOptions.isEmpty()) {
                ToastUtils.showLongToast("暂无筛选选项");
                return;
            }

            if (mDeviceStatusFilterPopup == null) {
                mDeviceStatusFilterPopup = new PopupWindow(getActivity());
                View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_spinner_popup, null);
                mDeviceStatusFilterPopupBinding = DataBindingUtil.bind(popupView);

                mDeviceStatusFilterPopup = new PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                mDeviceStatusFilterPopup.setFocusable(true);

                SimpleDataBindingPositionAdapter<String, ItemTextBinding> filterAdapter = new SimpleDataBindingPositionAdapter<String, ItemTextBinding>(getActivity(), R.layout.item_text, new DiffUtil.ItemCallback<String>() {
                    @Override
                    public boolean areItemsTheSame(@NonNull String oldItem, @NonNull String newItem) {
                        return oldItem.equals(newItem);
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull String oldItem, @NonNull String newItem) {
                        return oldItem.equals(newItem);
                    }
                }) {
                    @Override
                    protected void onBindItem(ItemTextBinding binding, String item, ViewHolder holder, int position) {
                        // 创建一个临时对象来显示文本
                        UserInfo.ProjectListBean tempBean = new UserInfo.ProjectListBean();
                        tempBean.setItemText(item);
                        binding.setVm(tempBean);
                    }
                };

                filterAdapter.submitList(mFilterOptions);
                mDeviceStatusFilterPopupBinding.setAdapter(filterAdapter);

                filterAdapter.setOnItemClickListener((viewId, item, position) -> {
                    mStates.selectedFilterName.set(item);
                    filterDeviceStatusList();
                    mDeviceStatusFilterPopup.dismiss();
                });
            }

            // 显示下拉弹窗
            View filterView = mBinding.getRoot().findViewById(R.id.tv_device_status_filter);
            if (filterView != null) {
                mDeviceStatusFilterPopup.showAsDropDown(filterView, 0, 0);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mAccountRequester.homeUnreadCount(UserInfo.getInstance().getProjectCode());
    }
}
